package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.code.BusinessBizCode;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.system.dao.SysLogininforDao;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.service.ISysLogininforService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;


/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author wintersnow
 * @since 1.0  2020-12-12
 */
@Transactional(readOnly = true)
@Service
public class SysLogininforServiceImpl implements ISysLogininforService {

    @Autowired
    private SysLogininforDao logininforDao;

    /**
     * 新增系统登录日志
     *
     * @param logininfor 访问日志对象
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertLogininfor(SysLogininfor logininfor) {
        logininfor.setLoginTime(new Date());
        logininforDao.save(logininfor);
    }

    /**
     * 查询系统登录日志集合
     *
     * @param req 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public Page<SysLogininfor> selectLogininforList(SysLogininfor req) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotNull(pageDomain.getPageNum()) && StringUtils.isNotNull(pageDomain.getPageSize())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        }
        Specification<SysLogininfor> example = new Specification<SysLogininfor>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<SysLogininfor> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNoneBlank(req.getIpaddr())) {
                    Predicate pre = cb.like(root.get("ipaddr").as(String.class), "%" + req.getIpaddr() + "%");
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getStatus())) {
                    Predicate pre = cb.equal(root.get("status").as(String.class), req.getStatus());
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getUserName())) {
                    Predicate pre = cb.like(root.get("userName").as(String.class), "%" + req.getUserName() + "%");
                    list.add(pre);
                }
                if (null != req.getParams().get("beginTime")) {
                    Predicate pre = cb.greaterThanOrEqualTo(root.get("loginTime").as(Date.class), DateUtils.parseDate(req.getParams().get("beginTime")));
                    list.add(pre);
                }
                if (null != req.getParams().get("endTime")) {
                    Predicate pre = cb.lessThanOrEqualTo(root.get("loginTime").as(Date.class), DateUtils.parseDate(req.getParams().get("endTime")));
                    list.add(pre);
                }
                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(), pageDomain.getPageSize(), Sort.Direction.DESC, Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("loginTime"));
        Page<SysLogininfor> page = logininforDao.findAll(example, pageable);
        return page;
    }

    /**
     * 批量删除系统登录日志
     *
     * @param infoIds 需要删除的登录日志ID
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteLogininforByIds(Long[] infoIds) {
        logininforDao.deleteAllByInfoIdIn(Arrays.asList(infoIds));
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 清空系统登录日志
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cleanLogininfor() {
        logininforDao.truncateTable();
    }
}
